//Global
import { useCallback } from "react";
import { useRouter } from "next/navigation";

//Actions
import {
  addUser,
  resetUser,
  setUser,
  setUsers,
} from "@/redux/reducers/userSlice";
import { postUserOrder, getOrders } from "@/redux/reducers/orderSlice";
import {
  changeModalLogInStatus,
  changeModalSignUpStatus,
} from "@/redux/reducers/modalsSlice";

//Hooks
import { useTypedSelector } from "./useTypedSelector";
import { useAppDispatch } from "./useAppDispatch";
import { useToastMessage } from "./useToastMessage";

//Types
import { IHandleFunctionParams, IOrder, IUser } from "@/types/types";

//Firebase
import firebase from "@/firebase";
import {
  createUserWithEmailAndPassword,
  getAuth,
  signInWithEmailAndPassword,
} from "firebase/auth";

//Utils
import { PROFILE_PAGE } from "@/utils/routes";

const useUserActions = () => {
  const { users } = useTypedSelector(state => state.user);
  const dispatch = useAppDispatch();
  const { push } = useRouter();
  const { showToastMessage } = useToastMessage();

  const functionSignUpUser = useCallback(
    (sighUpParams: IHandleFunctionParams) => {
      const auth = getAuth(firebase);

      const { email, password, name, reset, surname, phoneNumber } =
        sighUpParams;

      createUserWithEmailAndPassword(auth, email, password)
        .then(({ user }) => {
          const { email, uid, refreshToken } = user;

          const userObj: IUser = {
            name,
            surname,
            phoneNumber,
            email,
            id: uid,
            token: refreshToken,
            userCart: [],
          };

          dispatch(addUser(userObj));
          dispatch(setUser(userObj));

          showToastMessage(
            "success",
            "You've successfully created the account!"
          );
          dispatch(changeModalSignUpStatus(false));
          reset();
          push(PROFILE_PAGE);
        })
        .catch(() => {
          showToastMessage("error", "Something went wrong, try again!");
        });
    },
    [dispatch, push, showToastMessage]
  );

  const functionLogInUser = useCallback(
    (logInParams: IHandleFunctionParams) => {
      const auth = getAuth(firebase);

      const { email, password, reset } = logInParams;

      signInWithEmailAndPassword(auth, email, password)
        .then(({ user }) => {
          const foundedUser = users.find(
            arrUser => arrUser.email === user.email && arrUser.id === user.uid
          );

          if (foundedUser) dispatch(setUser(foundedUser));

          showToastMessage("success", "You've successfully logged in!");
          dispatch(changeModalLogInStatus(false));
          reset();
          push(PROFILE_PAGE);
        })
        .catch(() => {
          showToastMessage("error", "Uncorrect password or email, try again!");
        });
    },
    [dispatch, push, users, showToastMessage]
  );

  const logOut = () => {
    dispatch(resetUser()).catch(error => console.log(error));

    showToastMessage("success", "You've successfully logged out!");
  };

  const onSetUsers = useCallback(() => dispatch(setUsers()), [dispatch]);
  const onPostUserOrder = (order: IOrder) => dispatch(postUserOrder(order));
  const onGetUserOrders = useCallback(() => dispatch(getOrders()), [dispatch]);

  return {
    functionLogInUser,
    functionSignUpUser,
    logOut,
    onSetUsers,
    onPostUserOrder,
    onGetUserOrders,
  };
};

export { useUserActions };
